import { Controller } from "egg";

export default class DocumentController extends Controller {
  private async resolveUserId(): Promise<string | null> {
    const { ctx, service } = this;
    // 1) 优先从 session 读取（兼容 mockSession 与 SSO 设置）
    const sid = (ctx.session as any)?.userId || (ctx.session as any)?.user?.id;
    if (sid) return String(sid);

    // 2) 回退从 Cookie 读取 SSO_SESSION_ID 并验证
    const cookieSessionId = ctx.cookies.get("SSO_SESSION_ID", { signed: false });
    if (!cookieSessionId) return null;

    const result = await (service as any).userSequelize.validateSession(cookieSessionId);
    if (result?.success && result?.data?.user?.id) {
      // 缓存进 session，减少重复验证
      (ctx.session as any).userId = result.data.user.id;
      (ctx.session as any).username = result.data.user.username;
      return String(result.data.user.id);
    }
    return null;
  }
  // 文档列表（当前用户可见）
  public async list() {
    const { ctx, service } = this;
    const userId = await this.resolveUserId();
    if (!userId) {
      ctx.status = 401;
      ctx.body = { success: false, code: "UNAUTHORIZED", message: "未登录" };
      return;
    }
    const docs = await service.document.listUserDocuments(String(userId));
    ctx.body = { success: true, data: docs };
  }

  // 邀请协作（默认同意）
  public async invite() {
    const { ctx, service } = this;
    const inviterId = await this.resolveUserId();
    if (!inviterId) {
      ctx.status = 401;
      ctx.body = { success: false, code: "UNAUTHORIZED", message: "未登录" };
      return;
    }
    
    const { documentId } = ctx.params;
    const { userId, permission } = ctx.request.body || {};

    if (!documentId || !userId || !permission || !["read", "write", "admin"].includes(permission)) {
      ctx.status = 400;
      ctx.body = { success: false, code: "INVALID_PARAMS", message: "参数不完整或权限类型非法" };
      return;
    }

    const res = await service.document.inviteCollaborator(String(documentId), String(inviterId), String(userId), permission);
    if (!res.ok) {
      ctx.status = res.code === "NOT_FOUND" ? 404 : 403;
      ctx.body = { success: false, code: res.code, message: res.message };
      return;
    }

    ctx.body = { success: true, message: "邀请成功", data: res.data };
  }
  // 根据文档ID获取详情（校验用户访问权限）
  public async getById() {
    const { ctx, service } = this;
    const userId = await this.resolveUserId();
    if (!userId) {
      ctx.status = 401;
      ctx.body = { success: false, code: "UNAUTHORIZED", message: "未登录" };
      return;
    }
    const { documentId } = ctx.params;
    if (!documentId) {
      ctx.status = 400;
      ctx.body = { success: false, code: "INVALID_PARAMS", message: "文档ID不能为空" };
      return;
    }
    const doc = await service.document.getDocumentDetail(documentId, String(userId));
    if (!doc) {
      ctx.status = 404;
      ctx.body = { success: false, code: "NOT_FOUND", message: "文档不存在或无权限" };
      return;
    }
    ctx.body = { success: true, data: doc };
  }

  // 保存文档内容（BlockNote JSON）
  public async save() {
    const { ctx, service } = this;
    const userId = await this.resolveUserId();
    if (!userId) {
      ctx.status = 401;
      ctx.body = { success: false, code: "UNAUTHORIZED", message: "未登录" };
      return;
    }
    const { documentId } = ctx.params;
    const { content } = ctx.request.body || {};
    if (!documentId || content === undefined) {
      ctx.status = 400;
      ctx.body = { success: false, code: "INVALID_PARAMS", message: "缺少documentId或content" };
      return;
    }

    // 调试日志：记录接收到的内容类型和前几个字符
    console.log(`[文档保存] documentId: ${documentId}, content类型: ${typeof content}`);
    if (typeof content === 'string') {
      console.log(`[文档保存] content前100字符: ${content.substring(0, 100)}...`);
    } else {
      console.log(`[文档保存] content对象: ${JSON.stringify(content).substring(0, 100)}...`);
    }

    const res = await service.document.saveDocumentContent(documentId, String(userId), content);
    if (!res.ok) {
      if (res.code === "NOT_FOUND") {
        ctx.status = 404;
        ctx.body = { success: false, code: "NOT_FOUND", message: "文档不存在" };
        return;
      }
      ctx.status = 403;
      ctx.body = { success: false, code: "NO_PERMISSION", message: "没有保存权限" };
      return;
    }
    ctx.body = { success: true, message: "保存成功" };
  }

  // 创建文档（生成文档ID）
  public async create() {
    const { ctx, service } = this;
    const userId = await this.resolveUserId();
    if (!userId) {
      ctx.status = 401;
      ctx.body = { success: false, code: "UNAUTHORIZED", message: "未登录" };
      return;
    }
    const { title } = ctx.request.body || {};
    if (!title || typeof title !== "string" || !title.trim()) {
      ctx.status = 400;
      ctx.body = { success: false, code: "INVALID_PARAMS", message: "title 必填" };
      return;
    }
    const doc = await service.document.createDocument(String(userId), title.trim());
    ctx.body = { success: true, data: doc };
  }
}
